package com.cby.code.net.task;


import com.cby.code.net.Method;
import com.cby.code.net.Request;
import com.cby.code.net.RequestParam;
import com.cby.code.net.Response;
import com.cby.code.net.policy.RetryPolicy;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * @description: HttpUrlTask
 * @author: ChenBaoYang
 * @createDate: 2022/1/18 10:39 下午
 */
public class HttpUrlStringTask extends BaseTask{





    @Override
    public Response performRequest(Request request) {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            connection = createConnection(request);
            // 设置请求头
            setHeaders(connection, request.getParam());
            // 设置请求参数和请求方式
            setConnectionParametersForRequest(connection, request);
            // 解析相应数据
            return parseResponse(connection);
        } catch (Exception e) {
            RetryPolicy policy = request.getRetryPolicy();
            if(policy != null) {
                policy.retry(e);
            }
        }finally {
            closeConnection(connection);
        }
        return null;
    }

    /**
     * 解析响应数据信息
     * @param urlConnection
     */
    protected Response parseResponse(HttpURLConnection urlConnection) throws Exception {
        int httpStatus = urlConnection.getResponseCode();
        if (isOK(httpStatus)) {
            String result = streamToString(urlConnection.getInputStream());

            return new Response(result, httpStatus,"");
        } else {
            return new Response(null, httpStatus, urlConnection.getResponseMessage());
        }
    }
}
